const Proxy = require('../../proxy')
const webDataUtil = require('../../util/webDataUtil')
const axios = require('axios')

const BtbIndex = Proxy.BtbIndex

function parseValue (val) {
  return parseFloat(val || 0) || 0
}

// 获取我的账户信息
module.exports = async function () {
  const btbList = await BtbIndex.findWidthField({
    status: 1,
    xh_status: 1
  }, { code: 1, proportion: 1 }, {
    sort: '-proportion'
  })
  const pricesRes = await webDataUtil.binance('getPrices')
  const myPrice = pricesRes.data || {}
  const balanceResNew = await webDataUtil.binance('getBalance')
  const hl = await axios({
    method: 'get',
    url: `https://push2.eastmoney.com/api/qt/stock/get?secid=133.USDCNH&ut=f057cbcbce2a86e2866ab8877db1d059&forcect=1&fields=f43&invt=2&cb=jQuery18302206528858403829_1652938694805&wbp2u=|0|0|0|wap&_=1652938775453`
  }).then((data) => {
    let str = data.data.slice(data.data.indexOf('(') + 1, data.data.lastIndexOf(')'))
    let list = JSON.parse(str).data
    return list['f43'] || 0
  })
  const myBalanceNew = balanceResNew.data || {}
  let usdtSum = parseValue(myBalanceNew['USDT'].available)
  let hasUsdt = parseValue(myBalanceNew['USDT'].available)
  const usdtMap = {}
  const resultList = []
  btbList.forEach((btbItem) => {
    const usdtKey = `${btbItem.code}USDT`
    // 该笔的持仓，旧数据也没事，总金额变化不会很大
    const btbBalance = myBalanceNew[btbItem.code]
    const price = parseValue(myPrice[usdtKey])
    if (!btbBalance) {
      resultList.push({
        code: btbItem.code,
        proportion: btbItem.proportion,
        available: 0,
        price,
        usdt: 0
      })
      return false
    }
    const available = parseValue(btbBalance.available) || 0
    usdtMap[btbItem.code] = {
      proportion: btbItem.proportion,
      available,
      price,
      usdt: price * available
    }
    resultList.push({
      code: btbItem.code,
      proportion: btbItem.proportion,
      available,
      price,
      usdt: price * available
    })
    usdtSum += price * available
  })
  usdtMap['USDT'] = {
    proportion: 0,
    available: hasUsdt,
    price: 1,
    usdt: hasUsdt
  }
  usdtMap['ALL'] = {
    proportion: 0,
    usdt: usdtSum
  }
  return {
    // 汇率
    hl: parseFloat(hl) / 10000,
    ...usdtMap,
    btbList: resultList
  }
}
